<template>
    <section>
        <div class="cate-container">
            <div class="header">
                <h4>{{name}}</h4>
            </div>
            <div class="cate-con">
                <div class="cate-con__title flex-box flex-box-display">
                    <div>
                        <good-status :status.sync="goodStatus"></good-status>
                        <el-date-picker
                                v-model="createdTime"
                                type="date"
                                style="min-width:150px;"
                                placeholder="商品创建日期"
                                value-format="yyyy-MM-dd">
                        </el-date-picker>
                        <el-input v-model="goodName" placeholder="商品名称" style="width:150px;"></el-input>
                        <span>价格区间</span>
                        <el-input placeholder="" v-model="sale_price_one" style="width:50px;"></el-input>
                        <span>—</span>
                        <el-input placeholder="" v-model="sale_price_two" style="width:50px;"></el-input>
                    </div>

                    <el-button type="primary" @click="getGoodList" icon="el-icon-search"></el-button>
                </div>
                <div class="table-box">
                    <el-table :data="goodList" style="width: 100%">
                        <el-table-column :resizable="false" label="商品图">
                            <template slot-scope="scope">
                                <img :src="scope.row.image" style="width: 60px;height:60px;" v-if="scope.row.image"/>
                            </template>
                        </el-table-column>
                        <el-table-column :resizable="false" label="商品信息">
                            <template slot-scope="scope">
                                <span>{{scope.row.name}}<br>{{scope.row.title}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :resizable="false" label="售价" prop="market_price" sortable>
                        </el-table-column>
                        <el-table-column :resizable="false" label="所属分组">
                            <template slot-scope="scope">
                                <span v-if="scope.row.cat_name.length > 0"
                                      v-for="name in scope.row.cat_name">{{name}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :resizable="false" label="售卖状态">
                            <template slot-scope="scope">
                                <span v-if="scope.row.is_on_sale === 1">售卖中</span>
                                <span v-else>仓库中</span>
                            </template>
                        </el-table-column>
                        <el-table-column :resizable="false" label="创建时间" prop="created_at" sortable>
                        </el-table-column>
                        <el-table-column :resizable="false" label="组内商品排序" min-width="200">
                            <template slot-scope="scope">
                                <el-button @click="handleTop(scope.$index,scope.row.id,scope.row)" size="mini"
                                           class="icon-black icon-btn">
                                    <i class="fa fa-angle-double-up"></i>
                                </el-button>
                                <el-button @click="handleUp(scope.$index,scope.row.id,scope.row)" type="primary"
                                           size="mini"
                                           icon="el-icon-arrow-up" class="icon-btn"></el-button>
                                <el-button @click="handleDown(scope.$index,scope.row.id,scope.row)" type="info"
                                           size="mini"
                                           icon="el-icon-arrow-down" class="icon-btn"></el-button>
                                <el-button @click="handleBottom(scope.$index,scope.row.id,scope.row)" type="primary"
                                           size="mini"
                                           class="icon-black icon-btn">
                                    <i class="fa fa-angle-double-down"></i>
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column :resizable="false" prop="operation" label="操作" width="180">
                            <template slot-scope="scope">
                                <el-button @click="deleteItem(scope.$index,scope.row.id,scope.row)" type="primary">移除分组
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="pagination" v-if="page.total">
                    <div>
                        共{{page.count}}页，每页{{pageSize}}条
                    </div>
                    <el-pagination layout="prev, pager, next" :total="page.total" prev-text="上一页" next-text="下一页"
                                   :page-size="pageSize"
                                   @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </div>
        </div>
    </section>
</template>

<script>
    import FormRow from '../../components/basic/FlowRow';
    import GoodStatus from '../../components/Goodstatus';

    export default {
        components: {
            FormRow,
            GoodStatus
        },
        data() {
            return {
                name:'',
                id: '',
                goodStatus: '',
                createdTime: '',
                goodName: '',
                sale_price_one:'',
                sale_price_two:'',

                goodList: [],
                tableLoading: false,

                page: {
                    total: null,
                    count: null
                },
                pageSize: 20,
            }
        },
        watch: {},
        computed: {},
        created() {
            this.id = this.$route.query.id;
            this.name = this.$route.query.name;
        },
        mounted() {
            this.getGoodList();
        },
        methods: {
            genItem(data) {
                axios
                    .get('admin_goods', {
                        params: data
                    })
                    .then(res => {
                        this.page.total = res.data.count;
                        this.page.count = Math.ceil(res.data.count / this.pageSize);
                        return res;
                    })
                    .then(res => res.data.data)
                    .then(res => {
                        console.log('数据', res)
                        this.goodList = res;
                        if (res) {
                            this.goodList.forEach(item => {
                                item.cat_name = item.categories.length > 0 ? item.categories.map(item => {
                                    return item.name
                                }) : '';
                                item.slideshows = item.slideshow;
                                item.content_images = item.contents;
                                item.cat_id = item.categories.length > 0 ? item.categories.map(item => item.id).toString() : '';
                            })
                        }
                        this.tableLoading = false;
                    })
            },
            getGoodList(pagination=1) {
                const data = {
                    pagination,
                    pageSize: this.pageSize,
                    created_at: this.createdTime,
                    is_on_sale: this.goodStatus,
                    name: ['like', `%${this.goodName}%`],
                    cat_id: this.id,
                    sortBy: 'sort',
                    orderBy: 'asc',
                    sale_price: this.sale_price_one.length === 0 ? '' : ['between', `${this.sale_price_one},${this.sale_price_two}`],
                    // sale_price: ['exp', 'sale_price between(1,2)'],
                };
                console.log('搜索',data)
                this.genItem(data)
            },
            deleteItem(index, id, row) {
                const element = row;
                // element.slideshows = row.slideshow;
                // element.content_images = row.contents;
                element.categories.splice(element.categories.findIndex(item => item.id === this.id), 1);
                element.cat_id = element.categories.length > 0 ? element.categories.map(item => item.id).toString() : '';
                element._method = 'PUT';
                this.$confirm('确认是否将该商品移除分组?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        return axios
                            .post(`admin_goods/${id}`, element)
                            .then(
                                res => (res.data.status === 1 ? Promise.resolve() : Promise.reject(res.data.msg))
                            );
                    })
                    .then(() => {
                        this.$message({
                            type: 'success',
                            message: '移除商品成功!'
                        });
                        this.getGoodList();
                    })
                    .catch(err => {
                        if (err !== 'cancel') {
                            this.$message.error(err);
                        } else {
                            this.$message.error('取消');

                        }
                    });
            },
            //排序后向后台传递数据
            singlePost(data) {
                console.log('单挑数据', data)
                return axios
                    .post(`admin_goods/${data.id}`, data)
                    .then(
                        res => (res.data.status === 1 ? 'OK' : Promise.reject({msg: res.data.msg}))
                    );
            },
            postData(data) {
                console.log('上传', data);
                data.reduce((cur, next) => this.singlePost(cur).then(this.singlePost(next)))
                    .then(() => {
                        this.$message({
                            type: 'success',
                            message: '操作成功!'
                        });
                        this.getGoodList();
                    })
                    .catch(err => {
                        this.$message.error(err)
                    })

            },
            //上移
            handleUp(index, id, row) {
                console.log('上移', index, row);
                //this.goodList[index] 和 this.goodList[index-1] 的 sort 互换
                if (index > 0) {
                    const tem = this.goodList[index].sort;
                    console.log('互换值', tem)
                    this.goodList[index].sort = this.goodList[index - 1].sort;
                    this.goodList[index - 1].sort = tem;
                    const data = [];
                    data.push(this.goodList[index]);
                    data.push(this.goodList[index - 1]);
                    data[0]._method = 'PUT';
                    data[1]._method = 'PUT';
                    this.postData(data)
                } else {
                    this.$message({
                        message: '商品不能上移，已经置顶',
                        type: 'warning'
                    });
                }
            },
            //下移
            handleDown(index, id, row) {
                console.log('下移', index, row);
                if ((index + 1) === this.goodList.length) {
                    this.$message({
                        message: '商品不能下移，已经置底',
                        type: 'warning'
                    });
                } else {
                    console.log(index);
                    // let downDate = this.goodList[index + 1]
                    // this.goodList.splice(index + 1, 1);
                    // this.goodList.splice(index, 0, downDate);
                    const tem = this.goodList[index].sort;
                    console.log('互换值', tem)
                    this.goodList[index].sort = this.goodList[index + 1].sort;
                    this.goodList[index + 1].sort = tem;
                    const data = [];
                    data.push(this.goodList[index]);
                    data.push(this.goodList[index + 1]);
                    data[0]._method = 'PUT';
                    data[1]._method = 'PUT';
                    this.postData(data)
                }
            },
            //置顶
            handleTop(index, id, row) {
                //修改sort
                const topNum = this.goodList[0].sort;
                console.log('置顶', index, id, row)
                if (index === 0) {
                    this.$message({
                        message: '商品不能上移，已经置顶',
                        type: 'warning'
                    });
                } else {
                    axios
                        .post(`admin_goods/${id}`, this.genData(row, topNum - 1))
                        .then(
                            res => (res.data.status === 1 ? Promise.resolve() : Promise.reject(res.data.msg))
                        )
                        .then(() => {
                            // let topDate = this.goodList[index];
                            // let oneDate = this.goodList[0];
                            // this.goodList.splice(index, 1);
                            // this.goodList.splice(0, 0, topDate);
                            // this.goodList.solice(1, 0, oneDate)
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            });
                            this.getGoodList();
                        })
                        .catch(err => {
                            this.$message.error(err)
                        })
                }
            },
            //置底
            handleBottom(index, id, row) {
                //修改sort = 99999
                const lastNum = this.goodList[this.goodList.length - 1].sort;
                if ((index + 1) === this.goodList.length) {
                    this.$message({
                        message: '商品不能置底，已经是最后一条',
                        type: 'warning'
                    });
                } else {
                    console.log('更新数据', row);
                    axios
                        .post(`admin_goods/${id}`, this.genData(row, lastNum + 1))
                        .then(
                            res => (res.data.status === 1 ? Promise.resolve() : Promise.reject(res.data.msg))
                        )
                        .then(() => {
                            // let downDate = this.goodList[index];
                            // this.goodList.splice(index, 1);
                            // this.goodList.push(downDate);
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            });
                            this.getGoodList();
                        })
                        .catch(err => {
                            this.$message.error(err)
                        })
                }
            },
            genData(row, num) {
                const element = row;
                // element.slideshows = row.slideshow;
                // element.content_images = row.contents;
                // element.cat_id = element.categories.length > 0 ? element.categories.map(item => item.id).toString() : '';
                element.sort = num;
                element._method = 'PUT';
                return element
            },
            handleCurrentChange(current) {
                this.getGoodList(current);
            }
        }
    }
</script>
<style scoped>
    .cate-container {
        min-height: calc(100vh - 92px);
    }

    .flex-box {
        display: flex;
    }

    .flex-box-display {
        justify-content: space-between;
    }

    .header {
        padding: 10px;

        background: #FFFFFF;
    }

    .cate-con {
        margin: 10px;
        padding: 20px;
        background: #FFFFFF;
    }

    .cate-con__title {
        padding-bottom: 10px;
        border-bottom: 1px dashed #D8D8D8;
    }

    .table-box {
        min-height: calc(78vh - 92px);
    }

    .pagination {
        display: flex;
        align-items: center;
        justify-content: center;

        width: 100%;
    }

    .icon-btn {
        width: 20px;
        height: 20px;

        text-align: center;
        line-height: 20px;
    }

    .icon-black {
        color: #FFFFFF;
        background: #333333;
    }

</style>
<style>
    .el-button--mini, .el-button--mini.is-round {
        padding: 1px 4px;
    }
</style>